package com.whately.core.base.config.listener;

import org.apache.commons.lang3.StringUtils;
import org.springframework.boot.context.event.ApplicationEnvironmentPreparedEvent;
import org.springframework.boot.env.PropertiesPropertySourceLoader;
import org.springframework.boot.env.YamlPropertySourceLoader;
import org.springframework.context.ApplicationListener;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.PropertySource;
import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;

import java.io.IOException;
import java.util.List;

//不要注册
//@Component
public class LoadAdditionalPropertiesListener implements ApplicationListener<ApplicationEnvironmentPreparedEvent> {

    private ResourceLoader loader = new DefaultResourceLoader();

    //不同通过这种的方式获取
    //@Autowired
    //private Environment environment;

    @Override
    public void onApplicationEvent(ApplicationEnvironmentPreparedEvent event) {
        ConfigurableEnvironment environment = event.getEnvironment();
        try {
            String activeProfile = environment.getProperty("spring.profiles.active");


            //自定义properties文件
            //redis.properties文件
            //database.yml
            //TODO 2019-12-05 component 数据加载，读取database.yml 和 datasource-pool.properties
            //TODO 2020-10-10 custom.properties 和 redis.properties 也不需要使用配置文件，默认读取
            addProperties(activeProfile,environment,"custom.properties");
            addProperties(activeProfile,environment,"redis.properties");

            String additionalProperties = environment.getProperty("custom.config.propertyFiles");
            if(StringUtils.isNotBlank(additionalProperties)){
                String[] fileArray=additionalProperties.split(",");
                for(String file:fileArray){
                    if(StringUtils.isBlank(file)||file.trim().equals("custom.properties")|file.trim().equals("redis.properties")){
                        continue;
                    }
                    addProperties(activeProfile,environment,file);
                }
            }



            //自定义yml文件
            String additionalYml = environment.getProperty("custom.config.ymlFiles");

            if(StringUtils.isBlank(additionalYml)){
                additionalYml = "custom.yml";
            }

            String[] fileArray=additionalYml.split(",");
            for(String file:fileArray){
                if(StringUtils.isBlank(file)){
                    continue;
                }
                Resource resource = loader.getResource("classpath:profiles/"+activeProfile+"/"+file);
                if(resource!=null&&resource.exists()){
                    String fileName = file;
                    if(file.indexOf(".")>0){
                        fileName = file.substring(0,file.indexOf("."));
                    }
                    List<PropertySource<?>> yamlCustomProperties = new YamlPropertySourceLoader().load(activeProfile+"-"+fileName+"-CustomYml", resource);
                    if(yamlCustomProperties!=null){
                        for(PropertySource<?> p:yamlCustomProperties){
                            environment.getPropertySources().addFirst(p);
                        }
                    }
                }
            }
        }catch(IOException e){
            throw new IllegalStateException(e);
        }
    }

    private void addProperties(String activeProfile ,ConfigurableEnvironment environment,String fileNameOfProperties) throws IOException{
        Resource resource = loader.getResource("classpath:profiles/"+activeProfile+"/"+fileNameOfProperties);
        if(resource!=null&&resource.exists()){
            String fileName = fileNameOfProperties;
            if(fileNameOfProperties.indexOf(".")>0){
                fileName = fileNameOfProperties.substring(0,fileNameOfProperties.indexOf("."));
            }

            List<PropertySource<?>> propertySource = new PropertiesPropertySourceLoader().load(activeProfile+"-"+fileName+"-CustomProp",resource);
            if(propertySource!=null){
                for(PropertySource<?> p:propertySource){
                    environment.getPropertySources().addLast(p);
                }
            }
        }
    }
}
